// 封装请求
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'

export class Request {
  // axios 实例
  instance?: AxiosInstance

  //默认参数
  defaults = {
    baseUrl: '',
    url: '',
    data: null,
    params: null,
    method: 'get',
    header: {
      'Content-type': 'application/json'
    },
    timeout: 60000,
    isLoading: true //是否有加载特效
  }
  //拦截器
  interceptors = {
    request: (instance: AxiosInstance) => {},
    response: (instance: AxiosInstance) => {}
  }
  constructor(config: any) {
    this.defaults = Object.assign(this.defaults, config)
  }

  // 定义请求方法
  public request(config: AxiosRequestConfig) {
    this.instance = axios.create(this.defaults)
    this.interceptors.request(this.instance)
    this.interceptors.response(this.instance)
    return this.instance(config)
  }

  /**
   * get 方法
   * @param url 接口地址
   * @param data 接口参数
   * @param config 配置
   */
  get(url: string, params = {} as any | null, config = {} as any | null): Promise<AxiosResponse> {
    url = this.defaults.baseUrl + url
    return this.request(Object.assign({ url, params, method: 'get' }, config))
  }
  /**
   * delete 方法
   * @param url 接口地址
   * @param data 接口参数
   * @param config 配置
   */
  delete(url: string, data = {} as any | null, params = {} as any | null, config = {} as any | null): Promise<AxiosResponse> {
    url = this.defaults.baseUrl + url
    return this.request(Object.assign({ url, data, params, method: 'delete' }, config))
  }
  /**
   * post 方法
   * @param url 接口地址
   * @param data 接口参数
   * @param config 配置
   */
  post(url: string, data = {} as any | null, config = {} as any | null): Promise<AxiosResponse> {
    url = this.defaults.baseUrl + url
    return this.request(Object.assign({ url, data, method: 'post' }, config))
  }
  /**
   * put 方法
   * @param url 接口地址
   * @param data 接口参数
   * @param config 配置
   */
  put(url: string, data = {} as any | null, params = {} as any | null, config = {} as any | null): Promise<AxiosResponse> {
    url = this.defaults.baseUrl + url
    return this.request(Object.assign({ url, data, params, method: 'put' }, config))
  }
}
